package com.atung.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.atung.config.wx.WxPayConfig;
import com.atung.model.BusSchoolBusPayment;
import com.atung.request.RequestApplyRout;
import com.atung.request.RequestRoutApplication;
import com.atung.response.ResponsePublishPathList;
import com.atung.service.impl.PaySuessOrderService;
import com.atung.service.impl.RouteJourneyServiceImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.yuyi.full.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/wxRout")
@Api(tags="路线行程")
public class RouteJourneyController {
	@Autowired
	private RouteJourneyServiceImpl busRouteJourneyServiceImpl;
    private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private PaySuessOrderService paySuessOrderService;
	
	@GetMapping("/getPublishRout")
	@ApiOperation("获取发布路线信息列表")
	@ApiImplicitParam(name="data",value="data")
	public Result<List<ResponsePublishPathList>> selectBusRoutPublishByRoutId(@RequestParam Long routId,@RequestParam(required=false) String startDate) throws ParseException{
		Date dateStartDate=null;
		if(Objects.isNull(startDate)){
			dateStartDate=new Date(System.currentTimeMillis());
		}else{
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			dateStartDate = sf.parse(startDate);
		}
		List<ResponsePublishPathList>responsePublishPathLists=busRouteJourneyServiceImpl.selectBusRoutPublishByRoutId(routId, dateStartDate);
		return Result.success(responsePublishPathLists);
	}
	@GetMapping("/getCalendarDate")
	@ApiOperation("日历获取有车辆信息")
	public Result getCalendarDate(@RequestParam Long routId){
		Date startDate=new Date(System.currentTimeMillis());
		Set<String> clalendarDate=busRouteJourneyServiceImpl.selectCalendarDate(routId, startDate);
		return Result.success(clalendarDate);
	}
	
	@GetMapping("/getPublishRoutMessage")
	@ApiOperation("获取发布路线信息详情")
	public Result selectBusRoutPublishById(@RequestParam Long publisId){
		ResponsePublishPathList responsePublishPathLists=busRouteJourneyServiceImpl.selectBusRoutPublishById(publisId);
		return Result.success(responsePublishPathLists);
	}

	@PostMapping("/saveRoutApplication")
	@ApiOperation("申请路线路线")
	public Result insertBusRoutApplication(@RequestBody @Valid RequestRoutApplication request){	
		return busRouteJourneyServiceImpl.insertBusRoutApplication(request);
	}
	
	@PostMapping("/applyRout")
	@ApiOperation("路线报名")
	public Result applyRoutPublish(@RequestBody @Valid RequestApplyRout request){
		try {
			 Map<String, String> response=busRouteJourneyServiceImpl.applyRoutPublish(request);
			return Result.success(response);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			return  Result.error(201, e.getMessage());
		}
		
	}
	
    /**
     * 微信支付-回调接口
     * @param request
     * @throws Exception
     */
    @PostMapping(value="/wxNotify")
    public Result<?> notifyUrl(HttpServletRequest request) throws Exception{

        /**获取微信后台通知结果*/
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result  = new String(outSteam.toByteArray(),"utf-8");
        Map<String, String> map = WXPayUtil.xmlToMap(result);
        logger.info("异步通知：{}",map);
        /**定义返给微信后台的成功字段*/
        Map<String,String> resp = new HashMap<>();
        resp.put("return_code", "SUCCESS");
        resp.put("return_msg", "OK");
        String resStr = WXPayUtil.mapToXml(resp);
        /**校验签名是否正确*/
        boolean is = WXPayUtil.isSignatureValid(map,WxPayConfig.key, WXPayConstants.SignType.HMACSHA256);
        if (Objects.equals(is,true)) {
            logger.info("签名正确");
            /** 此处添加自己的业务逻辑代码 start */
            String out_trade_no =  map.get("out_trade_no");//商户订单号
            String transaction_id =  map.get("transaction_id");//微信支付订单号
            //格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010
            String time_end = (String) map.get("time_end");//支付完成时间
            Integer total_fee = Integer.valueOf(map.get("total_fee"));//订单金额（单位为分）
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            LocalDateTime timeEnd = LocalDateTime.parse(time_end,dtf);

            BusSchoolBusPayment busSchoolBusPayment =new BusSchoolBusPayment();
            busSchoolBusPayment.setId(Long.parseLong(out_trade_no));
           
            busSchoolBusPayment.setOrderPayTime(timeEnd);
            busSchoolBusPayment.setOrderPayMoney(new BigDecimal(total_fee).divide(new BigDecimal("100.00")));
            busSchoolBusPayment.setPaymentOrderNumber(transaction_id);
            busSchoolBusPayment.setOrderStatus(202);
            if(paySuessOrderService.updateBusSchoolBusPayment(busSchoolBusPayment)){
            	 //配车
                paySuessOrderService.paySuessOrder(Long.parseLong(out_trade_no));
            };
        }else{
            logger.info("签名不正确");
            return Result.success(resStr);
        }
		return null;
    }
}
